<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>07.canvasApi图片绘制</title>
</head>
<body>
<canvas id="canvas">

</canvas>

<script>
    window.onload = function () {
        console.log('onload');
        //获取canvas节点对象
        var canvasRef = document.querySelector('canvas');

        //设置canvas宽高
        canvasRef.width = 2000;
        canvasRef.height = 2000;
        canvasRef.style.border = "1px solid #000";
        //获取canvas上下文对象
        var ctx = canvasRef.getContext('2d');

        //获取图片对象
        var image = new Image();
        image.src = '../img/demo.jpg';
        image.alt = '测试图片'
        console.log(image)
        // ctx.drawImage(image,300,300); // 图片加载不成功
        //原因: 图片未加载完成 则调用图片对象绘制图案
        //解决:
        image.onload = function (){
            console.log('image onload complate');
            var imageWidth = image.width;
            var imageHeight = image.height;

            //自适应图片宽高比公式
            /*
            *       图片宽         设定宽
            *     ---------  =  ---------
            *       图片高         设定高
            * */

            //设定宽 让图片高度自适应
            // 设定高 = 设定宽 * 图片宽 / 图片高
            var setWidth = 900;
            var setHeight = setWidth * image.height  / image.width;
            // console.log(image.width)
            // console.log(image.height)
            console.log(setWidth)
            console.log(setHeight)
            ctx.drawImage(image,10,10,setWidth,setHeight);

        }
    }
</script>
</body>
</html>
